﻿using System;
using System . Collections . Generic;
using System . Linq;
using System . Text;
using System . Xml . Linq;

namespace WenceyWang . RichMan4L . Maps
{
	public class NormalRoad : Road
	{
		long forwardRoadID;

		Road forwardRoad = null;

		public virtual Road ForwardRoad { get { return forwardRoad ?? ( forwardRoad = Map . Currnet . GetRoad ( forwardRoadID ) ); } set { forwardRoadID = value . Id; forwardRoad = value; } }

		long backwardRoadID;

		Road backwardRoad = null;

		public virtual Road BackwardRoad { get { return backwardRoad ?? ( backwardRoad = Map . Currnet . GetRoad ( backwardRoadID ) ); } set { backwardRoadID = value . Id; backwardRoad = value; } }


		public override Path Route ( Road previous , int moveCount , Path result = null )
		{
			if ( previous == null )
			{
				throw new ArgumentNullException ( nameof ( previous ) );
			}
			if ( !CanEnter ( previous ) )
			{
				throw new ArgumentException ( "无法通过previous进入此道路" , nameof ( previous ) );
			}
			if ( moveCount < 0 )
			{
				throw new ArgumentOutOfRangeException ( nameof ( moveCount ) );
			}
			Path current = result ?? new Path ( );
			current . Route . Add ( this );
			if ( BlockMoving || moveCount == 0 )
			{
				return current;
			}
			else
			{
				if ( BackwardRoad == previous )
				{
					if ( ForwardRoad . CanEnter ( this ) )
					{
						return ForwardRoad . Route ( this , moveCount - 1 , current );
					}
					else
					{
						return BackwardRoad . Route ( this , moveCount - 1 , current );
					}
				}
				else
				{
					if ( BackwardRoad . CanEnter ( this ) )
					{
						return BackwardRoad . Route ( this , moveCount - 1 , current );
					}
					else
					{
						return ForwardRoad . Route ( this , moveCount - 1 , current );
					}
				}
			}
		}

		protected override void Dispose ( bool disposing )
		{
			ForwardRoad = null;
			BackwardRoad = null;
			base . Dispose ( disposing );
		}

		public override bool CanEnter ( Road road ) { return road == ForwardRoad || road == BackwardRoad; }

		public NormalRoad ( XElement resource ) : base ( resource )
		{
			forwardRoadID = Convert . ToInt64 ( resource . Attribute ( nameof ( ForwardRoad ) ) . Value );
			backwardRoadID = Convert . ToInt64 ( resource . Attribute ( nameof ( BackwardRoad ) ) . Value );
		}

	}
}
